package leetcodev1.数组;

public class LeetCode59 {

    public int[][] generateMatrix(int n) {
        int[][] ret = new int[n][n];
        int count = n * n, x = 0, y = 0;
        int[][] direct = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int directionIndex = 0;
        for (int i = 1; i <= count; i++) {
            ret[y][x] = i;
            int nextRow = y + direct[directionIndex][0], nextColumn = x + direct[directionIndex][1];
            //当前元素位置有问题，切换一下就好
            if (nextRow < 0 || nextRow >= n || nextColumn < 0 || nextColumn >= n || ret[nextRow][nextColumn] != 0) {
                directionIndex = (directionIndex + 1) % 4; // 顺时针旋转至下一个方向
            }
            y = y + direct[directionIndex][0];
            x = x + direct[directionIndex][1];
        }
        return ret;
    }
}
